package com.opennews.openplatform.controller;

import com.opennews.openplatform.myspringbootcore.dto.ApiResponse;
import com.opennews.openplatform.myspringbootmvccore.helper.HttpResponseHelper;
import com.opennews.openplatform.service.AppReleaseLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequiredArgsConstructor
@RestController
@RequestMapping("/app-release-log")
public class AppReleaseLogController {
    private final Environment env;
    private final AppReleaseLogService appReleaseLogService;
    private final HttpResponseHelper httpResponseHelper;

    @GetMapping("/query-by-app-version")
    public ResponseEntity<ApiResponse<Map<String, Object>>> queryByAppVersion(@RequestParam String appVersion) {
        Map<String, Object> result = appReleaseLogService.queryByAppVersion(appVersion);

        return httpResponseHelper.getSuccessResponse(result);
    }

    @GetMapping("/query-latest-version")
    public ResponseEntity<ApiResponse<Map<String, Object>>> queryLatestVersion(@RequestParam String appVersion) {
        Map<String, Object> appInfo = appReleaseLogService.queryLatestVersion(appVersion);

        Map<String, Object> result = new HashMap<>();
        result.put("hasUpdate", appInfo != null);

        // Map.of() Behavior
        // Immutable Map: Map.of() creates an immutable map where neither keys nor values can be null.
        // Throws Exception: If you attempt to pass null as either a key or a value, it throws a NullPointerException.
        // Because appInfo might be null. That's why Map.of() is NOT applicable here.
        result.put("appInfo", appInfo);

        result.put("sharingH5Url", String.format("%s/%s/app-sharing.html",
                env.getProperty("resource.httpBaseUrl"),
                env.getProperty("resource.h5DirectoryName")));

        return httpResponseHelper.getSuccessResponse(result);
    }

    @GetMapping("/list-change-log")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> listChangeLog(@RequestParam int pageSize, @RequestParam int pageIndex) {
        List<Map<String, Object>> result = appReleaseLogService.listChangeLog(pageSize, pageIndex);

        return httpResponseHelper.getSuccessResponse(result);
    }
}
